import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Card, Button, Row, Input, Col, Select, Table, Modal, Checkbox } from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import { routerRedux } from 'dva/router';

import { getParamUrl } from '../../utils/formatDataSource';

const CheckboxGroup = Checkbox.Group;
const Option = Select.Option;

@connect(({ studentDetailConfig, loading }) => ({
  studentDetailConfig,
  loading: loading.effects['studentDetailConfig/getTotalStudents'],
}))
class StudentHome extends PureComponent {
  state = {
    visible: false,
    name: '',
    campus: '0',
    classId: '0',
    status: '0',
    homeClass: {
      class: [],
      campus: [],
    },
    studentList: {
      total: 0,
      data: [],
    },
    checkboxData: [],
    currentUser: {},
  };
  componentDidMount = () => {
    this.props
      .dispatch({
        type: 'studentDetailConfig/totalClasses',
      })
      .then(() => {
        this.setState({ homeClass: this.props.studentDetailConfig.homeClass });
      });
    this.getTableData();
  };
  getTableData = value => {
    const { campus, classId, status } = this.state;
    const { dispatch } = this.props;
    if (!value) {
      value = {};
    }
    let param = {
      campus,
      classId,
      status,
      ...value,
    };
    dispatch({
      type: 'studentDetailConfig/getTotalStudents',
      payload: param,
    }).then(() => {
      const { studentList } = this.props.studentDetailConfig;
      this.setState({
        studentList,
      });
    });
  };
  columns = () => {
    return [
      {
        title: '学生姓名',
        dataIndex: 'name',
        key: 'name',
        align: 'center',
      },
      {
        title: '年级',
        dataIndex: 'grade',
        key: 'grade',
        align: 'center',
      },
      {
        title: '性别',
        dataIndex: 'sex',
        key: 'sex',
        align: 'center',
      },
      {
        title: '所在校区',
        dataIndex: 'school',
        key: 'school',
        align: 'center',
      },
      {
        title: '所在班级',
        key: 'class',
        align: 'center',
        render: item => {
          const { classList } = item;
          const str = classList.map(c => c.name).join('、');
          return <span>{str}</span>;
        },
      },
      {
        title: '状态',
        dataIndex: 'manageStatus',
        key: 'manageStatus',
        align: 'center',
        render: value => {
          return this.getStatusName(value);
        },
      },
      {
        title: '学习状态',
        dataIndex: 'learnStatus',
        key: 'learnStatus',
        align: 'center',
        render: value => {
          let msg = '';
          if (value === 1) {
            msg = '进步';
          } else if (value === 2) {
            msg = '问题';
          } else if (value === 3) {
            msg = '稳定';
          }
          return <span>{msg}</span>;
        },
      },
      {
        title: '操作',
        key: 'action',
        align: 'center',
        render: record => {
          return (
            <div>
              <a
                href="javascript:;"
                onClick={() => this.toDetailPage(record)}
                hidden={this.getHidden(1)}
              >
                查看
              </a>&nbsp;&nbsp;
              <a
                href="javascript:;"
                onClick={() => {
                  this.showModal(record);
                }}
                hidden={this.getHidden(2)}
              >
                签约提交
              </a>
            </div>
          );
        },
      },
    ];
  };
  toDetailPage = record => {
    sessionStorage.setItem('backRef', '/lesson/studentManage/home');
    this.props.dispatch(
      routerRedux.push(`/studentManage/student/info?studentId=${record.studentId}`)
    );
  };
  showModal = student => {
    const { signSubject } = student;
    if (signSubject) {
      const arr = signSubject.split(',');
      this.setState({ checkboxData: arr });
    } else {
      this.setState({ checkboxData: [] });
    }
    setTimeout(() => {
      this.setState({
        visible: true,
        currentUser: student,
      });
    }, 100);
  };
  getHidden = type => {
    const loginUserStr = sessionStorage.getItem('current-user');
    if (loginUserStr) {
      const loginUser = JSON.parse(loginUserStr);
      const authority = loginUser.roles.map(r => r.code);
      if (type === 1) {
        if (authority.indexOf('teacher') > -1 || authority.indexOf('educounselor') > -1) {
          return false;
        } else {
          return true;
        }
      } else if (type === 2) {
        if (authority.indexOf('educounselor') > -1) {
          return false;
        } else {
          return true;
        }
      }
    } else {
      return true;
    }
  };
  getStatusName = status => {
    switch (status) {
      case 1:
        return <span>未签约</span>;
      case 2:
        return <span>待分班</span>;
      case 3:
        return <span style={{ color: '#008000' }}>已就读</span>;
      case 4:
        return <span style={{ color: '#CC0000' }}>已毕业</span>;
      case 5:
        return <span>已暂停</span>;
      default:
        return '';
    }
  };
  handleCampus = value => this.setState({ campus: value });
  handleClass = value => this.setState({ classId: value });
  handleStatus = value => this.setState({ status: value });
  confirmOk = () => {
    const { dispatch } = this.props;
    const { checkboxData, currentUser, studentList: { data } } = this.state;
    const subject = checkboxData.join(',');
    if (currentUser.signSubject === subject) {
      this.setState({ visible: false });
      return;
    }
    dispatch({
      type: 'studentDetailConfig/saveStudentSubject',
      payload: {
        subject,
        studentId: currentUser.studentId,
      },
    }).then(() => {
      currentUser.signSubject = subject;
      currentUser.manageStatus = 2;
      this.setState({
        studentList: {
          data: [...data],
        },
      });
    });
    this.setState({ visible: false });
  };
  confirmCancel = () => {
    this.setState({
      visible: false,
    });
  };
  checkboxChange = value => {
    this.setState({ checkboxData: value });
  };
  search = () => {
    const { name, campus, classId, status } = this.state;
    const { studentList: { data } } = this.props.studentDetailConfig;
    let newData = data.filter(d => {
      if (name !== '') {
        if (!d.name) {
          d.name = '';
        }
        return d.name.indexOf(name) > -1;
      } else {
        return true;
      }
    });
    if (campus !== '0') {
      newData = newData.filter(d => d.school === campus);
    }
    if (classId !== '0') {
      newData = newData.filter(d => {
        let { classList } = d;
        return classList.map(c => c.id).indexOf(classId) > -1;
      });
    }
    if (status !== '0') {
      newData = newData.filter(d => d.manageStatus + '' === status);
    }
    this.setState({
      studentList: {
        data: newData,
      },
    });
  };
  getDisabled = subject => {
    const { currentUser: { signSubject } } = this.state;
    if (signSubject) {
      const signArr = signSubject.split(',');
      return signArr.indexOf(subject) > -1 ? true : false;
    } else {
      return false;
    }
  };
  render = () => {
    const { homeClass, campus, classId, status, studentList } = this.state;
    console.log(studentList);
    return (
      <PageHeaderLayout>
        <Card style={{ minHeight: '790px' }}>
          <Row align="middle">
            <Col span={4}>
              查询：
              <Input
                style={{ width: '70%' }}
                placeholder="姓名"
                value={this.state.name}
                onChange={e =>
                  this.setState({
                    name: e.target.value,
                  })
                }
              />
            </Col>
            <Col span={4}>
              校区：
              <Select
                defaultValue="全部"
                style={{ width: '70%' }}
                onChange={this.handleCampus}
                value={campus}
              >
                <Option value="0">全部</Option>
                {homeClass.campus.map((c, i) => (
                  <Option value={c.name} key={c.id}>
                    {c.name}
                  </Option>
                ))}
              </Select>
            </Col>
            <Col span={4}>
              班级：
              <Select
                defaultValue="全部"
                style={{ width: '70%' }}
                onChange={this.handleClass}
                value={classId}
              >
                <Option value="0">全部</Option>
                {homeClass.class.map((c, i) => (
                  <Option value={c.id} key={c.id}>
                    {c.name}
                  </Option>
                ))}
              </Select>
            </Col>
            <Col span={4}>
              状态：
              <Select
                defaultValue="全部"
                style={{ width: '70%' }}
                onChange={this.handleStatus}
                value={status}
              >
                <Option value="0">全部</Option>
                <Option value="1">未签约</Option>
                <Option value="2">待分班</Option>
                <Option value="3">已就读</Option>
                <Option value="4">已毕业</Option>
                <Option value="5">已暂停</Option>
              </Select>
            </Col>
            <Col span={8} style={{ textAlign: 'right' }}>
              <Button type="primary" size="small" onClick={this.search}>
                查询
              </Button>
            </Col>
          </Row>
          <br />
          <Table
            dataSource={studentList.data}
            columns={this.columns()}
            loading={this.props.loading}
            onChange={this.handleChange}
          />
          <Modal
            title="请选择签约科目"
            visible={this.state.visible}
            onOk={this.confirmOk}
            onCancel={this.confirmCancel}
          >
            <CheckboxGroup
              style={{ width: '100%' }}
              onChange={this.checkboxChange}
              value={this.state.checkboxData}
            >
              <Row>
                <Col span={8}>
                  <Checkbox value="1" disabled={this.getDisabled('1')}>
                    数学
                  </Checkbox>
                </Col>
                <Col span={8}>
                  <Checkbox value="2" disabled={this.getDisabled('2')}>
                    语文
                  </Checkbox>
                </Col>
                <Col span={8}>
                  <Checkbox value="3" disabled={this.getDisabled('3')}>
                    英语
                  </Checkbox>
                </Col>
                <Col span={8}>
                  <Checkbox value="4" disabled={this.getDisabled('4')}>
                    物理
                  </Checkbox>
                </Col>
                <Col span={8}>
                  <Checkbox value="5" disabled={this.getDisabled('5')}>
                    化学
                  </Checkbox>
                </Col>
                <Col span={8}>
                  <Checkbox value="6" disabled={this.getDisabled('6')}>
                    生物
                  </Checkbox>
                </Col>
                <Col span={8}>
                  <Checkbox value="8" disabled={this.getDisabled('8')}>
                    历史
                  </Checkbox>
                </Col>
                <Col span={8}>
                  <Checkbox value="9" disabled={this.getDisabled('9')}>
                    政治
                  </Checkbox>
                </Col>
                <Col span={8}>
                  <Checkbox value="7" disabled={this.getDisabled('7')}>
                    地理
                  </Checkbox>
                </Col>
              </Row>
            </CheckboxGroup>
          </Modal>
        </Card>
      </PageHeaderLayout>
    );
  };
}

export default StudentHome;
